import NavBar from '@/components/NavBar'
import { DatePicker, List, Drawer, Toast, Modal } from 'antd-mobile'
import { useEffect, useRef, useState } from 'react'
import { useDispatch } from 'react-redux'
import { useHistory } from 'react-router-dom'
import {
  getUserProfile,
  updatephoto,
  updateProfile,
} from '@/store/action/profile'
import styles from './index.module.scss'
import { useSelector } from 'react-redux'
import classNames from 'classnames'
import Editlnput from './EditInput/index'
import EditList from './EditList/index'
import dayjs from 'dayjs'
import { onlogout } from '@/store/action/login'
const Edit = () => {
  // 获取 Redux Store 中个人详情
  const { birthday, gender, intro, name, photo } = useSelector(
    (state) => state.profile.userProfile
  )
  const [open, setopen] = useState({
    visible: false,
    type: '',
  })
  const close = () => {
    setopen({
      visible: false,
      type: '',
    })
    setlist({
      visible: false,
      type: '',
    })
  }
  const [list, setlist] = useState({
    visible: false,
    type: '',
  })
  const onCommit = (type, value) => {
    dispatch(updateProfile({ [type]: value }))
    Toast.success('修改成功')
    close()
  }
  const history = useHistory()
  const dispatch = useDispatch()
  useEffect(() => {
    dispatch(getUserProfile())
  }, [dispatch])
  const fileRef = useRef(null)
  const onFileChange = async (e) => {
    const file = e.target.files[0]
    const fd = new FormData()
    fd.append('photo', file)
    await dispatch(updatephoto(fd))
    Toast.success('修改头像成功')
    close()
  }
  const onBirthange = (e) => {
    onCommit('birthday', dayjs(e).format('YYYY-MM-DD'))
  }
  const onlogoutFn = () => {
    Modal.alert('退出', '确认要退出吗', [
      {
        text: '取消',
      },
      {
        text: '确认',
        onPress() {
          dispatch(onlogout())
          Toast.success('退出登录成功')
          history.push('/login')
        },
      },
    ])
  }
  // 头像、性别配置
  const config = {
    photo: [
      {
        title: '拍照',
        onClick: () => {
          alert('暂不支持此功能')
        },
      },
      {
        title: '本地选择',
        onClick: () => {
          fileRef.current.click()
        },
      },
    ],
    gender: [
      {
        title: '男',
        onClick: () => {
          onCommit('gender', 0)
        },
      },
      {
        title: '女',
        onClick: () => {
          onCommit('gender', 1)
        },
      },
    ],
  }

  return (
    <div className={styles.root}>
      <div className="content">
        {/* 顶部导航栏 */}
        <NavBar onLeftClick={() => history.go(-1)}>个人信息</NavBar>

        <div className="wrapper">
          {/* 列表一：显示头像、昵称、简介 */}
          <List className="profile-list">
            <List.Item
              arrow="horizontal"
              onClick={() => {
                setlist({ visible: true, type: 'photo' })
              }}
              extra={
                <span className="avatar-wrapper">
                  <img src={photo} alt="" />
                </span>
              }
            >
              头像
            </List.Item>

            <List.Item
              arrow="horizontal"
              extra={name}
              onClick={() => {
                setopen({ visible: true, type: 'name' })
              }}
            >
              昵称
            </List.Item>

            <List.Item
              arrow="horizontal"
              extra={
                <span className={classNames('intro', intro ? 'normal' : '')}>
                  {intro || '未填写'}
                </span>
              }
              onClick={() => {
                setopen({ visible: true, type: 'intro' })
              }}
            >
              简介
            </List.Item>
          </List>

          {/* 列表二：显示性别、生日 */}
          <List className="profile-list">
            <List.Item
              arrow="horizontal"
              extra={gender ? '女' : '男'}
              onClick={() => {
                setlist({ visible: true, type: 'gender' })
              }}
            >
              性别
            </List.Item>
            <DatePicker
              mode="date"
              title="选择年月日"
              value={new Date(birthday)}
              minDate={new Date(1900, 1, 1, 0, 0, 0)}
              maxDate={new Date()}
              onChange={(e) => {
                onBirthange(e)
              }}
            >
              <List.Item arrow="horizontal" extra={birthday}>
                生日
              </List.Item>
            </DatePicker>
          </List>

          {/* 文件选择框，用于头像图片的上传 */}
          <input type="file" hidden ref={fileRef} onChange={onFileChange} />
        </div>

        {/* 底部栏：退出登录按钮 */}
        <div className="logout">
          <button className="btn" onClick={onlogoutFn}>
            退出登录
          </button>
        </div>
      </div>
      {open.type ? (
        <Drawer
          className="drawer"
          style={{ minHeight: document.documentElement.clientHeight }}
          children={''}
          sidebar={
            <Editlnput
              close={close}
              type={open.type}
              onCommit={onCommit}
            ></Editlnput>
          }
          open={open.visible}
        ></Drawer>
      ) : (
        ''
      )}

      {/* 头像、性别 */}
      <Drawer
        className="drawer-list"
        position="bottom"
        children={''}
        onOpenChange={close}
        sidebar={
          list.type ? (
            <EditList
              config={config}
              type={list.type}
              onClose={close}
              onCommit={onCommit}
            />
          ) : (
            ''
          )
        }
        open={list.visible}
      ></Drawer>
    </div>
  )
}

export default Edit
